import asyncio

import timeout_decorator
from aiohttp import ClientSession
from aiohttp import TCPConnector
import datetime
import json
import logging
from utils.log_util import setup_log
import math
from common_dir.common_def import timeout_exec
import time
import random
from insert_sql import insert_etl_db


logger = setup_log("baidu_toufang")


class aiohttp_post_baidu:

    def __init__(self):

        # 获取所有子帐号URL
        self.get_child_url = "https://api.baidu.com/json/feed/v1/MccFeedService/getUserListByMccid"
        self.last_date = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime('%Y-%m-%d')
        # 获取原生消费
        self.yuansheng_child_cost_url = "https://api.baidu.com/json/feed/v1/ReportFeedService/getRealTimeFeedData"

        # 获取搜索消费
        self.search_child_cost_url = "https://api.baidu.com/json/sms/service/ReportService/getRealTimeData"

        self.http_headers = {
            "Accept-Encoding": "gzip, deflate",
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

    # 所有子帐号消费
    async def all_child_cost(self, semaphore, url, all_child_cost_list, butler_name, butler_password, single_child,
                             butler_token, reportType):
        # body
        user_payload = {
            "header": {
                "username": butler_name,
                "password": butler_password,
                "target": single_child,
                "token": butler_token,
                "action": "API-PYTHON"
            },
            "body": {
                "realTimeRequestType": {
                    "producttype": 0,
                    "endDate": self.last_date,
                    "levelOfDetails": 2,
                    "number": 1000,
                    "order": "true",
                    "performanceData": [
                        "cost",
                        "impression",
                        "click",
                        "cpm",
                        "ctr",
                        "cpc"
                    ],
                    "reportType": reportType,
                    "startDate": self.last_date,
                    "statRange": 2,
                    "unitOfTime": 5,
                    "bstype": 0
                }
            }
        }
        async with semaphore:
            async with ClientSession(connector=TCPConnector(verify_ssl=False)) as session:
                async with session.post(url=url, data=json.dumps(user_payload), headers=self.http_headers) as resp:
                    all_dict = await resp.json()
                    if all_dict["header"]["desc"] == "success":
                        if len(all_dict["body"]["data"]) == 0:
                            logger.info(butler_name + ", " + single_child + ", " + str(0))
                            all_child_cost_list.append(0)
                        else:
                            logger.info(
                                butler_name + ", " + single_child + ", " + all_dict["body"]["data"][0]["kpis"][0])
                            all_child_cost_list.append(all_dict["body"]["data"][0]["kpis"][0])

    async def child_main(self, url, all_child_len, butler_name, butler_password, butler_token, reportType,
                         all_child_name):
        semaphore = asyncio.Semaphore(10)
        tasks = [
            self.all_child_cost(semaphore, url, all_child_len, butler_name, butler_password, single_child, butler_token,
                                reportType) for
            single_child in all_child_name
        ]
        await asyncio.wait(tasks, timeout=88)

    # 所有子帐号name
    async def get_all_child_list(self, company, butler_name, butler_token, butler_password):
        user_payload = {
            "header": {
                "authorityType": 0,
                "username": butler_name,
                "token": butler_token,
                "password": butler_password,
                "action": "API-PYTHON"
            },
            "body": {}
        }
        async with ClientSession(connector=TCPConnector(verify_ssl=False)) as session:
            async with session.post(url=self.get_child_url, data=json.dumps(user_payload),
                                    headers=self.http_headers) as resp:
                all_dict = await resp.json()
                all_child_len = all_dict["header"]["succ"]
                all_child_name = []
                for single in all_dict["body"]["data"]:
                    all_child_name.append(single["username"])
                if all_child_len == len(all_child_name):
                    logger.info("管家帐号：" + butler_name + "，子帐号总数目：" + str(all_child_len))
                    all_child_cost_list = []
                    try_num = 0
                    while len(all_child_cost_list) != all_child_len:
                        if company == "yuansheng":
                            url = self.yuansheng_child_cost_url
                            reportType = 700
                            await self.child_main(url, all_child_cost_list, butler_name, butler_password, butler_token,
                                                  reportType, all_child_name)
                        elif company == "search":
                            url = self.search_child_cost_url
                            reportType = 2
                            await self.child_main(url, all_child_cost_list, butler_name, butler_password, butler_token,
                                                  reportType, all_child_name)

                        else:
                            all_child_cost_list = []

                        if try_num == 5:
                            break
                        try_num += 1
                        time.sleep(round(random.uniform(2.71, 4.59), 1))
                        logger.info("第" + str(try_num) + "次请求, 请求接口获取的子帐号数目：" + str(len(all_child_cost_list)))

                    if len(all_child_cost_list) == all_child_len:
                        logger.info(
                            butler_name + ": " + str(math.ceil((sum(list(map(float, all_child_cost_list)))) * 100)))
                        return math.ceil((sum(list(map(float, all_child_cost_list)))) * 100)
                else:
                    logging.info("succ:" + str(all_child_len) + ",all_child_name_len:" + str(len(all_child_len)))

    def main(self, name_password_list, big_channel):

        loop = asyncio.get_event_loop()
        tasks = asyncio.gather(*[
            self.get_all_child_list(single_info["company"], single_info["butler_name"], single_info["butler_token"],
                                    single_info["butler_password"]) for single_info in name_password_list])
        results = loop.run_until_complete(tasks)
        #loop.close()
        sum_xiaofei = int(sum(list(map(float, results))))
        if sum_xiaofei:
            insert_etl_db(str(sum_xiaofei), 'toufang_sembaidu', big_channel).insert_mysql()


@timeout_exec
@timeout_decorator.timeout(360, use_signals=True)
def xinpuys():

    name_password_list = [{"company": "yuansheng", "butler_name": "123原生账户管家", "butler_password": "pwd",
                           "butler_token": "toker"}]
    aiohttp_post_baidu().main(name_password_list, "xinpuys")


@timeout_exec
@timeout_decorator.timeout(360, use_signals=True)
def xinpu():

    name_password_list = [
        {"company": "search", "butler_name": "123xp账户管家", "butler_password": "pwd", "butler_token": "token"},
        {"company": "search", "butler_name": "123xp-黑龙江", "butler_password": "pwd", "butler_token": "token"}
                        ]

    aiohttp_post_baidu().main(name_password_list, "xinpu")


if __name__ == '__main__':
    xinpuys()
    xinpu()

